﻿//-----------------------------------------------------------------------
// <copyright file="AddRemoveEntityAction.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace TileTool.Scene.Action
{
    using System;
    using TileTool.Action;
    using TileTool.Log;
    using TileTool.Scene.Entity;

    /// <summary>
    /// Action to add / remove entities in a scene.
    /// </summary>
    public class AddRemoveEntityAction : SceneAction
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "AddEntityAction";

        #endregion

        #region Fields - Private

        /// <summary>
        /// Bool which tracks if we will add or remove entities to the scene on Do().
        /// </summary>
        private bool add;

        /// <summary>
        /// Entities that we are going to add.
        /// </summary>
        private IEntityCollection entities;

        /// <summary>
        /// Previous selection.
        /// </summary>
        private IEntityCollection previousSelection;

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor for the action.
        /// </summary>
        /// <param name="scene">Scene we will add or remove from.</param>
        /// <param name="ents">Entities to add or remove.</param>
        /// <param name="add">Whether or not we will add entities to the scene on Do().</param>
        public AddRemoveEntityAction(ISceneManager scene, IEntityCollection ents, bool add) 
            : base(scene)
        {
            if (scene == null)
            {
                throw new ArgumentNullException("scene", "Scene must be non-null.");
            }

            if (ents == null)
            {
                throw new ArgumentNullException("ents", "Entity collection must be non-null..");
            }

            this.add = add;
            this.entities = this.BuildEntityCollection(ents);
            this.previousSelection = scene.Selection;
            this.Valid = this.entities.Count != 0;
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Do the action.
        /// </summary>
        public override void Do()
        {
            if (!this.Valid)
            {
                return;
            }

            LogSystem.LogInfo(LogGroup, "Do() - Validating data...");
            this.ValidateDataForDo();

            string addRemoveString = this.add ? "Adding" : "Removing";
            LogSystem.LogInfo(LogGroup, "Do() - " + addRemoveString + " " + this.entities.Count + " entities.");

            if (this.add)
            {
                this.Scene.AddEntities(this.entities);
            }
            else
            {
                this.Scene.RemoveEntities(this.entities);
                this.Scene.SetSelection(new EntityCollection());
            }
        }

        /// <summary>
        /// Undo the action.
        /// </summary>
        public override void Undo()
        {
            if (!this.Valid)
            {
                return;
            }

            LogSystem.LogInfo(LogGroup, "Undo() - Validating data...");
            this.ValidateDataForUndo();

            string addRemoveString = this.add ? "Removing" : "Adding";
            LogSystem.LogInfo(LogGroup, "Undo() - " + addRemoveString + " " + this.entities.Count + " entities.");

            if (this.add)
            {
                this.Scene.RemoveEntities(this.entities);
            }
            else
            {
                this.Scene.AddEntities(this.entities);
                this.Scene.SetSelection(this.previousSelection);
            }
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Will build the collection of entities that we will add / remove. This method
        /// will traverse children to ensure that the entire entity tree is added or removed.
        /// </summary>
        /// <param name="entities">Input set of entities to start the build from.</param>
        /// <returns>Returns a collection of entities to add / remove.</returns>
        private IEntityCollection BuildEntityCollection(IEntityCollection entities)
        {
            IEntityCollection res = new EntityCollection();

            this.BuildEntityCollectionRecurse(entities, res);

            return res;
        }

        /// <summary>
        /// Recursively add entities to the result collection.
        /// </summary>
        /// <param name="entities">Input set of entities to build from.</param>
        /// <param name="res">Result entity collection to add to.</param>
        private void BuildEntityCollectionRecurse(IEntityCollection entities, IEntityCollection res)
        {
            foreach (IEntity entity in entities)
            {
                res.Add(entity);

                IEntityCollection children = entity.Children;
                if (children.Count != 0)
                {
                    this.BuildEntityCollectionRecurse(children, res);
                }
            }
        }

        /// <summary>
        /// Validate our data before we execute a Do().
        /// </summary>
        private void ValidateDataForDo()
        {
            foreach (IEntity entity in this.entities)
            {
                if (this.add)
                {
                    if (entity.Scene != null)
                    {
                        throw new InvalidOperationException("Entity must have a null scene reference to be added to a scene.");
                    }
                }
                else
                {
                    if (entity.Scene == null)
                    {
                        throw new InvalidOperationException("Entity must have a non-null scene reference to be removed from a scene.");
                    }
                }
            }
        }

        /// <summary>
        /// Validate our data before we execute a Undo().
        /// </summary>
        private void ValidateDataForUndo()
        {
            foreach (IEntity entity in this.entities)
            {
                if (this.add)
                {
                    if (entity.Scene == null)
                    {
                        throw new InvalidOperationException("Entity must have a non-null scene reference to be removed from a scene.");
                    }
                }
                else
                {
                    if (entity.Scene != null)
                    {
                        throw new InvalidOperationException("Entity must have a null scene reference to be added to a scene.");
                    }
                }
            }
        }

        #endregion
    }
}
